package com.dbecom.platform.foundation.batch.listener;

import javax.sql.DataSource;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.batch.core.ItemProcessListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.util.StringUtils;

import com.dbecom.platform.foundation.batch.ECBatchException;

public class LogProcessListener implements ItemProcessListener<Object, Object> {

    private static final Log log = LogFactory.getLog(LogProcessListener.class);

    private JdbcTemplate jdbcTemplate;
    
    @Autowired
    @Qualifier("batchDataSource")
    DataSource batchDataSource;

    private static final String INSERT_BATCH_VALIDATION_ERROR = "insert into BATCH_VALIDATION_ERROR "
            + "(JOB_EXECUTION_ID,"
            + "LINE_NUMBER,"
            + "FIELD,"
            + "ERROR_CODE,"
            + "ERROR_ARGS,"
            + "DEFAULT_MESSAGE)"
            + " values(?,?,?,?,?,?)";

    public void afterProcess(Object item, Object result) {
        log.info("Input to Processor: " + item.toString());
        log.info("Output of Processor: " + result.toString());
    }

    public void beforeProcess(Object item) {
        this.jdbcTemplate = new JdbcTemplate(batchDataSource);
    }

    public void onProcessError(Object item, Exception ex) {
        if (ex instanceof ECBatchException) {
            ECBatchException batchEx = (ECBatchException) ex;
            jdbcTemplate.update(INSERT_BATCH_VALIDATION_ERROR, batchEx.getJobExecutionId(), batchEx.getLineNumber(),
                    batchEx.getField(), batchEx.getErrorCode(),
                    StringUtils.arrayToCommaDelimitedString(batchEx.getErrorArgs()), batchEx.getDefaultMessage());
        } else {
            log.error("error: " + item.toString() + " ==> exception: " + ex);
        }

    }

}
